<!--
 * @Descripttion: 保养计划表单
 * @LastEditors: xzh
 * @LastEditTime: 2023-09-15 21:55:48
-->
<template>
  <DileDrawer
    v-model="upkeepPlanForm.visible"
    :loading="upkeepPlanForm.loading"
    size="80%"
    @sure="hanldeSure"
  >
    <template #header>
      <span>{{
        $t(`table.btnArr.${!upkeepPlanForm.formData.id ? "add" : "edit"}`)
      }}</span>
    </template>
    <template #default>
      <el-form
        ref="formRef"
        class="el-form-card"
        :model="upkeepPlanForm.formData"
        :rules="formRules"
        label-width="7rem"
        size="large"
        status-icon
      >
        <!-- 模具信息 -->
        <el-card>
          <template #header>
            <span>{{ $t("page.moldManageArr.moldArchivesArr.moldInfo") }}</span>
          </template>
          <el-col :span="12">
            <el-form-item
              :label="$t('page.moldManageArr.moldArchivesArr.name')"
              prop="relMold.name"
            >
              <el-input
                v-model="upkeepPlanForm.formData.relMold.name"
                readonly
                :placeholder="$t('common.select')"
                @click="() => dileSelectItemTableRef.init()"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              :label="$t('page.moldManageArr.moldArchivesArr.code')"
            >
              <el-input
                v-model="upkeepPlanForm.formData.relMold.code"
                disabled
                :placeholder="$t('common.systemAutoBringOut')"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              :label="$t('page.moldManageArr.moldArchivesArr.factory')"
            >
              <el-input
                v-model="upkeepPlanForm.formData.relMold.extJson.factoryName"
                disabled
                :placeholder="$t('common.systemAutoBringOut')"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('page.moldManageArr.moldType')">
              <el-input
                v-model="upkeepPlanForm.formData.relMold.extJson.typeName"
                disabled
                :placeholder="$t('common.systemAutoBringOut')"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('page.systemManageArr.position')">
              <el-input
                v-model="upkeepPlanForm.formData.relMold.extJson.positionName"
                disabled
                :placeholder="$t('common.systemAutoBringOut')"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              :label="$t('page.moldManageArr.moldArchivesArr.department')"
            >
              <el-input
                v-model="upkeepPlanForm.formData.relMold.extJson.departmentName"
                disabled
                :placeholder="$t('common.systemAutoBringOut')"
              />
            </el-form-item>
          </el-col>
        </el-card>
        <!-- 计划信息 -->
        <el-card>
          <template #header>
            <span>{{ $t("page.equipUpkeepArr.upkeepPlanArr.planInfo") }}</span>
          </template>
          <el-col :span="12">
            <el-form-item :label="$t('page.equipUpkeepArr.upkeepPlanArr.code')">
              <el-input
                v-model="upkeepPlanForm.formData.code"
                disabled
                :placeholder="$t('common.systemAutoGenerate')"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              :label="$t('page.equipUpkeepArr.upkeepPlanArr.name')"
              prop="name"
            >
              <el-input
                v-model="upkeepPlanForm.formData.name"
                :placeholder="$t('common.enter')"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              :label="$t('page.equipUpkeepArr.upkeepPlanArr.startDate')"
              prop="startDate"
            >
              <el-date-picker
                v-model="upkeepPlanForm.formData.startDate"
                type="datetime"
                :placeholder="$t('common.selectDateTime')"
                value-format="YYYY-MM-DD HH:mm:ss"
                :disabled-date="(time:any) => dayjs(time).isAfter(upkeepPlanForm.formData.endDate)"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              :label="$t('page.equipUpkeepArr.upkeepPlanArr.endDate')"
              prop="endDate"
            >
              <el-date-picker
                v-model="upkeepPlanForm.formData.endDate"
                type="datetime"
                :placeholder="$t('common.selectDateTime')"
                value-format="YYYY-MM-DD HH:mm:ss"
                :disabled-date="(time:any) => dayjs(time).isBefore(upkeepPlanForm.formData.startDate)"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item
              :label="$t('page.equipUpkeepArr.upkeepPlanArr.planType')"
              prop="planType"
            >
              <el-select
                v-model="upkeepPlanForm.formData.planType"
                :placeholder="$t('common.select')"
              >
                <el-option
                  v-for="planType in Object.keys(upkeepPlanTypeEnum)"
                  :key="planType"
                  :label="
                    $t(
                      `page.equipUpkeepArr.upkeepPlanArr.planTypeArr.${planType}`
                    )
                  "
                  :value="planType"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item
              :label="$t('page.equipUpkeepArr.upkeepPlanArr.executeRule')"
              prop="executeRuleId"
              :validate-status="
                !!upkeepPlanForm.formData.executeRuleId ? 'success' : ''
              "
            >
              <!-- 输入框选择对象 -->
              <DileInputSelectItem
                v-model="upkeepPlanForm.formData.executeRuleId"
                :expand-on-click-node="false"
                :selectType="selectTypeEnum.executeRule"
                :cacheLabel="upkeepPlanForm.formData.relExecuteRule.name"
                @itemSelected="handleExecuteRuleSelected"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item
              :label="$t('page.equipUpkeepArr.upkeepPlanArr.executeRuleRemark')"
            >
              <el-input
                v-model="upkeepPlanForm.formData.relExecuteRule.ruleDescription"
                :rows="5"
                type="textarea"
                disabled
                :placeholder="$t('common.systemAutoBringOut')"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item
              :label="$t('page.equipUpkeepArr.upkeepPlanArr.planStatus')"
            >
              <el-radio-group v-model="upkeepPlanForm.formData.status">
                <el-radio :label="true">{{
                  $t(`page.equipUpkeepArr.upkeepPlanArr.planStatusArr.start`)
                }}</el-radio>
                <el-radio :label="false">{{
                  $t(`page.equipUpkeepArr.upkeepPlanArr.planStatusArr.close`)
                }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item :label="$t('common.remark')">
              <el-input
                v-model="upkeepPlanForm.formData.remark"
                :rows="5"
                type="textarea"
              />
            </el-form-item>
          </el-col>
        </el-card>
        <!-- 保养人员 -->
        <el-card>
          <template #header>
            <span>{{
              $t("page.equipUpkeepArr.upkeepPlanArr.upkeepPeople")
            }}</span>
          </template>
          <el-col :span="12">
            <el-form-item :label="$t('page.equipUpkeepArr.upkeepPlanArr.team')">
              <!-- 输入框选择对象 -->
              <DileInputSelectItem
                v-model="upkeepPlanForm.formData.teamId"
                :expand-on-click-node="false"
                :selectType="selectTypeEnum.team"
                :cacheLabel="upkeepPlanForm.formData.extJson.teamName"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              :label="$t('page.equipUpkeepArr.upkeepPlanArr.manager')"
            >
              <!-- 输入框选择对象 -->
              <DileInputSelectItem
                v-model="upkeepPlanForm.formData.manager"
                :selectType="selectTypeEnum.people"
                :cacheLabel="upkeepPlanForm.formData.extJson.managerName"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item
              :label="$t('page.equipUpkeepArr.upkeepPlanArr.otherPeople')"
            >
              <!-- 输入框选择对象 -->
              <DileInputSelectItem
                v-model="upkeepPlanForm.formData.otherUser"
                :selectType="selectTypeEnum.people"
                :cacheLabel="upkeepPlanForm.formData.extJson.otherPeopleName"
                multiple
              />
            </el-form-item>
          </el-col>
        </el-card>
        <!-- 保养项目 -->
        <el-card>
          <template #header>
            <span>{{ $t("page.equipUpkeepArr.upkeepItem") }}</span>
          </template>
          <!-- 关联保养项目 -->
          <RelUpkeepItem ref="relUpkeepItemRef" />
        </el-card>
      </el-form>
    </template>
  </DileDrawer>
  <!-- 选择对象列表 -->
  <DileSelectItemTable
    ref="dileSelectItemTableRef"
    :selectTableType="selectTableTypeEnum.mold"
    :multiple="false"
    @sure="handleMoldSelected"
  />
</template>

<script setup lang="ts">
import { ref, reactive, toRefs, computed, nextTick, toRef } from "vue";
import type { object_Inf } from "@/utils/typings/index.type";
import { useI18n } from "vue-i18n";
import { ElNotification, dayjs } from "element-plus";
import {
  selectTableTypeEnum,
  selectTypeEnum,
} from "@/components/dile-selectItem/index.type";
import { upkeepPlanTypeEnum } from "@/utils/typings/equipManage/equipUpkeep/index.type";
import DileInputSelectItem from "@/components/dile-selectItem/selectItem-input/index.vue";
import DileSelectItemTable from "@/components/dile-selectItem/selectItem-table/index.vue";
import RelUpkeepItem from "@/views/moldManage/moldUpkeep/upkeepItem/upkeepItem-relTable/index.vue";
import DileDrawer from "@/components/dile-drawer/index.vue";
import Dile_APi from "@/api";

const emit = defineEmits(["refresh"]);

let { t } = useI18n();
/**
 * @Author: xzh
 * @Descripttion: 选择对象表格实例
 * @Param:
 */
let dileSelectItemTableRef = ref<any>(null);
/**
 * @Author: xzh
 * @Descripttion: 关联保养项目表格实例
 * @Param:
 */
let relUpkeepItemRef = ref<any>(null);
/**
 * @Author: xzh
 * @Descripttion: 表单实例
 * @Param:
 */
let formRef = ref<any>(null);

/**
 * @Author: xzh
 * @Descripttion: 表单默认数据
 * @Param:
 */
let defaultData = () => ({
  id: 0,
  status: true, //状态
  mouldId: null,
  //模具信息
  relMold: {
    name: "", //模具名称
    code: "", //模具编码
    extJson: {
      factoryName: "", //所在工厂名称
      typeName: "", //模具类型名称
      positionName: "", //存放位置
      departmentName: "", //使用部门名称
    },
  },
  //计划信息
  code: "", //计划编号
  name: "", //计划名称
  startDate: "", //计划开始时间
  endDate: "", //计划结束时间
  planType: "", //计划类型
  executeRuleId: null, //执行规则
  relExecuteRule: {
    name: "", //模具名称
    ruleDescription: "", //执行规则描述
  },
  remark: "", //备注
  //保养人员
  teamId: null, //保养班组
  manager: null, //保养负责人
  otherUser: "", //其他保养人
  extJson: {
    teamName: "", //保养班组名称
    managerName: "", //保养负责人名称
    otherPeopleName: "", //其他保养人名称
  },
});
/**
 * @Author: xzh
 * @Descripttion: 保养计划表单参数
 * @Param:
 */
let upkeepPlanForm = reactive<object_Inf>({
  visible: false,
  loading: false,
  //表单数据
  formData: defaultData(),
  resoure: {
    //模具状态
    equipStateArr: [],
    //模具存放位置
    equipPositionArr: [],
  },
});

/**
 * @Author: xzh
 * @Descripttion:表单验证规则
 * @Param:
 * @param {*} computed
 */
let formRules = computed((): any => {
  return reactive({
    ["relMold.name"]: [
      {
        required: true,
        message:
          t("common.enter") + t("page.moldManageArr.moldArchivesArr.name"),
        trigger: "change",
      },
    ],
    name: [
      {
        required: true,
        message:
          t("common.enter") + t("page.equipUpkeepArr.upkeepPlanArr.name"),
        trigger: "change",
      },
    ],
    startDate: [
      {
        required: true,
        message:
          t("common.select") + t("page.equipUpkeepArr.upkeepPlanArr.startDate"),
        trigger: "change",
      },
    ],
    endDate: [
      {
        required: true,
        message:
          t("common.select") + t("page.equipUpkeepArr.upkeepPlanArr.endDate"),
        trigger: "change",
      },
    ],
    planType: [
      {
        required: true,
        message:
          t("common.select") + t("page.equipUpkeepArr.upkeepPlanArr.planType"),
        trigger: "change",
      },
    ],
    executeRuleId: [
      {
        required: true,
        message:
          t("common.select") +
          t("page.equipUpkeepArr.upkeepPlanArr.executeRule"),
        trigger: "change",
      },
    ],
  });
});

/**
 * @Author: xzh
 * @Descripttion:初始化加载
 * @Param:
 * @param {*} id 保养计划主键
 */
let init = async (id: number) => {
  let { visible, loading } = toRefs(upkeepPlanForm);
  visible.value = true;
  await nextTick();
  try {
    loading.value = true;
    //加载表单数据
    await initFormData(id);
  } finally {
    loading.value = false;
  }
};

/**
 * @Author: xzh
 * @Descripttion: 加载表单数据
 * @Param:
 */
let initFormData = async (id: number) => {
  let {
    model,
    mouldInfoModel,
    executeRuleModel,
    dataList,
    relations,
  }: object_Inf = !!id
    ? await Dile_APi.getMoldUpkeepPlanInfo(id)
    : { model: defaultData(), mouldInfoModel: {}, executeRuleModel: {} };
  Object.assign(upkeepPlanForm.formData, {
    ...model,
    relMold: { ...model.relMold, ...mouldInfoModel },
    relExecuteRule: { ...model.relExecuteRule, ...executeRuleModel },
  });
  //格式化关联备件信息
  if (dataList?.length > 0) {
    let relUpkeepItemArr = dataList
      .map((upkeepItem: object_Inf) => {
        let { id } = relations?.find(
          (x: object_Inf) => x.maintenanceProjectId == upkeepItem.id
        );
        return !!id
          ? {
              ...upkeepItem,
              relId: id,
            }
          : {};
      })
      .filter((x: object_Inf) => !!x.id);
    //加载关联保养项目表格
    relUpkeepItemRef.value.initTableData(relUpkeepItemArr);
  }
};

/**
 * @Author: xzh
 * @Descripttion: 模具选中事件
 * @Param:
 * @param {*} mold
 */
let handleMoldSelected = (moldArr: object_Inf) => {
  let { formData } = toRefs(upkeepPlanForm),
    mold = moldArr.find(() => true);
  Object.assign(formData.value, {
    ...formData.value,
    mouldId: mold.id,
    relMold: mold,
  });
};
/**
 * @Author: xzh
 * @Descripttion: 执行规则选择事件
 * @Param:
 * @param {*} executeRuleArr
 */
let handleExecuteRuleSelected = (executeRuleArr: Array<object_Inf>) => {
  let { formData } = toRefs(upkeepPlanForm),
    executeRule = executeRuleArr.find(() => true);
  Object.assign(formData.value.relExecuteRule, executeRule);
};
/**
 * @Author: xzh
 * @Descripttion: 保存事件
 * @Param:
 */
let hanldeSure = async () => {
  let { formData, loading, visible } = toRefs(upkeepPlanForm),
    valid = await formRef.value.validate();
  if (!valid || !!loading.value) {
    return false;
  }
  try {
    loading.value = true;

    let { id } = formData.value,
      relData: object_Inf = relUpkeepItemRef.value.getRelData();
    //格式化关联保养项目信息
    Object.keys(relData)
      .filter((x) => x != "deleteRelations")
      .forEach(
        (relkey) =>
          (relData[relkey] = relData[relkey].map((x: object_Inf) => {
            let { id: upkeepItemId, relId } = x;
            return {
              id: relId,
              maintenanceProjectId: upkeepItemId,
              maintenancePlanId: id,
            };
          }))
      );

    await Dile_APi.saveMoldUpkeepPlan({
      model: formData.value,
      ...relData,
    });
    //触发刷新回调
    emit("refresh");
    //提示成功
    ElNotification({
      message: t("common.message.OperationSuccess"),
      type: "success",
    });
    //关闭弹框
    visible.value = false;
  } finally {
    loading.value = false;
  }
};

defineExpose({
  init,
});
</script>
<style lang="scss" scoped></style>
